package com.authine.cloudpivot.ext.applicationservice;

import cn.hutool.core.date.DateUtil;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.*;
import com.authine.cloudpivot.ext.dto.VendorTradeNumStastics.VendorOrderTradeReturnStastics;
import com.authine.cloudpivot.ext.dto.VendorTradeNumStastics.VendorOrderTradeStastics;
import com.authine.cloudpivot.ext.dto.VendorTradeNumStastics.VendorQuotationTradeStastics;
import com.authine.cloudpivot.ext.enums.report.ReportType;
import com.authine.cloudpivot.ext.utils.*;
import com.authine.cloudpivot.ext.utils.system.ReportUtils;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.dto.bo.query.ListBOQuery;
import com.authine.mvp.app.launcher.dto.bo.query.expression.*;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Slf4j
@Path("GoodTradeStatisticInfoService")
public class GoodTradeStatisticInfoService extends ApplicationService {

    /**
     * @return 商品交易量统计
     */
    @Path("queryGoodTradeStatistic")
    @POST
    @Operation(summary = "商品交易量统计", tags = CUSTOM_SERVICE)
    public com.alibaba.cola.dto.SingleResponse<BOList> queryGoodTradeStatistic(@Parameter GoodTradeStatisticInfoDto good) {
        ListBOQuery listBOQuery = new ListBOQuery();
        listBOQuery.setSchemaCode(ModelConst.T_GOODS_PURCHASE);
        List<Condition> conditions = new ArrayList<>();
        if (StringUtils.isNotEmpty(good.getCreateStartTime())){
            conditions.add(new SimpleCondition("createdTime", Operator.GTE, good.getCreateStartTime()));
        }
        if (StringUtils.isNotEmpty(good.getVendor_name())){
            conditions.add(new SimpleCondition("vendor_name", Operator.LIKE, good.getVendor_name()));
        }
        if (StringUtils.isNotEmpty(good.getCreateEndTime())){
            conditions.add(new SimpleCondition("createdTime", Operator.LTE, good.getCreateEndTime()));
        }
        if (StringUtils.isNotEmpty(good.getName())){
            conditions.add(new SimpleCondition("name", Operator.LIKE, good.getName()));
        }
        if (StringUtils.isNotEmpty(good.getBrand())){
            conditions.add(new SimpleCondition("brand", Operator.LIKE, good.getBrand()));
        }
        if (StringUtils.isNotEmpty(good.getModel())){
            conditions.add(new SimpleCondition("model", Operator.LIKE, good.getModel()));
        }
        if (conditions != null && conditions.size() > 0 ){
            ComplexCondition complexCondition = new ComplexCondition();
            complexCondition.setNature(Nature.AND);
            complexCondition.setConditions(conditions);
            listBOQuery.setCondition(complexCondition);
        }

        listBOQuery.setPageIndex(good.getPageIndex());
        listBOQuery.setPageSize(good.getPageSize());
        // 获取报表导出列表
        SingleResponse<BOList> goods = boService.list(listBOQuery);
        List<Map<String, Object>> data = goods.getData().getData();

        List<String> list = new ArrayList<>();
        if (data != null && data.size() > 0){
            data.forEach(item->{
                String goodName = (String) item.get("name");
                list.add(goodName);
            });
        }

        List<Map<String, Object>> maps = VendorStasticsJdbcUtil.queryVendorOrder(list);
        log.info("maps:{}",maps);
        if (data != null && data.size() > 0){
            data.forEach(item->{
                String name = (String) item.get("name");
                if (maps != null && maps.size() > 0){
                    maps.forEach(item2->{
                        String good_name = (String) item2.get("name");
                        if(StringUtils.equals(name,good_name)){
                            item.put("quantity",item2.get("orderNumber"));
                            item.put("totalPrice",item2.get("orderTotal"));
                        }
                    });
                }
            });
        }


        List<Map<String, Object>> quotations = VendorStasticsJdbcUtil.queryGoodPurchaseGroupBy(list);
        log.info("maps:{}",maps);
        if (data != null && data.size() > 0){
            data.forEach(item->{
                String name = (String) item.get("name");
                if (quotations != null && quotations.size() > 0){
                    quotations.forEach(item2->{
                        String good_name = (String) item2.get("name");
                        if(StringUtils.equals(name,good_name)){
                            item.put("quotationNumber",item2.get("quotationNumber"));
                            item.put("quotationTotal",item2.get("quotationTotal"));
                        }
                    });
                }
            });
        }
        return goods;
    }

    /**
     * @return 商品交易量统计导出
     */
    @Path("exportGoodTrade")
    @POST
    @Operation(summary = "商品交易量统计导出", tags = CUSTOM_SERVICE)
    public SingleResponse exportGoodTrade(@Parameter GoodTradeStatisticInfoDto good) {
        ReportType reportType = ReportType.get(good.getFileType());
        List<Map<String, Object>> maps = VendorStasticsJdbcUtil.queryGoodPurchase(good);
        if (maps != null && maps.size() > 0){
            String exportField = "{\"vendor_name\":\"vendor_name\",\"name\":\"name\",\"brand\":\"brand\",\"model\":\"model\",\"orderNumber\":\"orderNumber\",\"orderTotal\":\"orderTotal\",\"quotationNumber\":\"quotationNumber\",\"quotationTotal\":\"quotationTotal\"}";
            JSONObject exportJson = JSON.parseObject(exportField);
            List<Map<String, Object>> fileData = maps.stream().map(m -> {
                Map<String, Object> mf = new HashMap<>();
                for (String key : exportJson.keySet()) {
                    mf.put(exportJson.getString(key), m.get(key));
                }
                return mf;
            }).collect(Collectors.toList());
            ReportUtils.exportReport("commodity_tradingVolume_report", reportType.getId(), fileData);
            return SingleResponse.buildSuccess();
        }else{
            return SingleResponse.buildFailure("-1", "未获取到下载数据");
        }

    }



    /**
     * @return 虚拟供应商报价统计
     */
    @Path("queryVirtualVendorStatistic")
    @POST
    @Operation(summary = "虚拟供应商报价统计", tags = CUSTOM_SERVICE)
    public com.alibaba.cola.dto.SingleResponse<BOList> queryVirtualVendorStatistic(@Parameter VirtualVendorStatisticDto good) {
        PageObject<Map<String,Object>> pageObject = new PageObject<Map<String,Object>>();
        List<Map<String, Object>> orderList = new ArrayList<>();
        int count = 0;
        try{
            Integer pageCurrent = good.getPageCurrent() == null ?  1: good.getPageCurrent();
            Integer pageSize = good.getPageSize() == null ? 10 : good.getPageSize();
            // 设置当前页
            good.setPageCurrent(pageCurrent);
            // 设置每页显示的条数
            pageObject.setPageSize(pageSize);
            // 设置总记录数

            count = QuotationGoodJdbcUtil.getQuotationGoodCountSql(good);
            log.info("总条数:{}"+count);
            pageObject.setRowCount(count);
            pageObject.setPageCount(0);
            if (count != 0 ) {
                // 设置总页数
                int pageNum = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
                pageObject.setPageCount(pageNum);
                // 设置每页显示数据集合
                // 开始的记录数
                int start = (pageCurrent - 1) * pageSize;
                System.out.println(start + "-" + pageSize);
                orderList = QuotationGoodJdbcUtil.getQuotationGoodList(good, start, pageSize);
            }
        }catch (Exception e){
            log.info("查询出错",e);
        }

        BoResultFormat.resultFormat(orderList, "dfgmwvswcq9s");
        BOList bOList = new BOList();
        bOList.setData(orderList);
        bOList.setTotal(count);
        bOList.setSchemaCode("dfgmwvswcq9s");
        return com.alibaba.cola.dto.SingleResponse.of(bOList);
    }


    @Path("vendorTradeStatistic")
    @POST
    @Operation(summary = "供应商交易量统计",tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> vendorTradeStatistic(@Parameter VendorStatsticsDto vendor){

        int count = 0;
        List<Map<String, Object>> vendors = new ArrayList<>();
        PageObject<VendorData> pageObject = new PageObject<VendorData>();
        try{
            Integer pageCurrent = vendor.getPageCurrent() == null ?  1: vendor.getPageCurrent();
            Integer pageSize = vendor.getPageSize() == null ? 10 : vendor.getPageSize();

            // 设置当前页
            vendor.setPageCurrent(pageCurrent);
            // 设置每页显示的条数
            pageObject.setPageSize(pageSize);
            // 设置总记录数

            count = VendorStasticsJdbcUtil.queryAllVendorCount(vendor);
            log.info("总条数:{}"+count);
            pageObject.setRowCount(count);
            pageObject.setPageCount(0);
            if (count != 0 ) {
                // 设置总页数
                int pageNum = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
                pageObject.setPageCount(pageNum);
                // 设置每页显示数据集合
                // 开始的记录数
                int start = (pageCurrent - 1) * pageSize;
                System.out.println(start + "-" + pageSize);
                vendors = getMaps(vendor, pageSize, start);

            }
        }catch(Exception e){
            log.info("查询出错",e);
        }
        BoResultFormat.resultFormat(vendors, ModelConst.T_VENDOR_TRADE_NUM_STATISTIC);
        BOList bOList = new BOList();
        bOList.setData(vendors);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_VENDOR_TRADE_NUM_STATISTIC);
        return com.alibaba.cola.dto.SingleResponse.of(bOList);
    }

    @NotNull
    private List<Map<String, Object>> getMaps(VendorStatsticsDto vendor, Integer pageSize, Integer start) {
        StringBuffer sbNames = new StringBuffer();
        List<Map<String, Object>> vendors = VendorStasticsJdbcUtil.queryAllVendor(vendor, start, pageSize);
        if (vendors != null && vendors.size() > 0){
            vendors.forEach(item->{
                String name = (String) item.get("name");
                if (StringUtils.isNotBlank(name)){
                    sbNames.append(name);
                    sbNames.append(",");
                }
            });
        }
        sbNames.deleteCharAt(sbNames.length() - 1);
        List<VendorQuotationTradeStastics> vendorQuotationTradeStastics = VendorStasticsJdbcUtil.queryQuotationStatistic(vendor, sbNames);
        //报价
        buildVendorQuotationTradeStastics(vendorQuotationTradeStastics, vendors);

        //订单
        StringBuffer sbStatus = new StringBuffer();
        sbStatus.append("UpcomingPayment");
        sbStatus.append("UpcomingConfirm");
        sbStatus.append("UpcomingDelivery");
        sbStatus.append("Closed");

        List<VendorOrderTradeStastics> vendorOrderTradeStastics = VendorStasticsJdbcUtil.queryVendorOrderTradeStastics(vendor, sbNames, sbStatus);
        buildVendorOrderTradeStastics(vendorOrderTradeStastics, vendors);

        //退货

        List<VendorOrderTradeReturnStastics> returns = VendorStasticsJdbcUtil.queryVendorOrderTradeReturnStastics(vendor, sbNames);
        buildVendorOrderTradeReturnStastics(returns, vendors);
        return vendors;
    }


    private void buildVendorOrderTradeReturnStastics(List<VendorOrderTradeReturnStastics> returns, List<Map<String, Object>> vendors) {
        if (vendors != null
                && vendors.size() > 0
                && returns != null
                && returns.size() > 0){
            vendors.forEach(item->{
                String name = (String) item.get("name");
                returns.forEach(item2->{
                    String vendor_organization_name = item2.getVendor_organization_name();
                    if (StringUtils.equals(name,vendor_organization_name)){
                        item.put("refund_num",item2.getRefund_num());
                        item.put("refund_total",item2.getRefund_total());
                    }
                });
            });
        }


    }

    private void buildVendorOrderTradeStastics(List<VendorOrderTradeStastics> stasticsList, List<Map<String, Object>> vendors) {
        if (vendors != null
                && vendors.size() > 0
                && stasticsList != null
                && stasticsList.size() > 0){
            vendors.forEach(item->{
                String name = (String) item.get("name");
                stasticsList.forEach(item2->{
                    String vendor_organization_name = item2.getVendor_organization_name();
                    if (StringUtils.equals(name,vendor_organization_name)){
                        item.put("orderGoodNum",item2.getOrderGoodNum());
                        item.put("orderAmount",item2.getOrderAmount());
                    }
                });
            });
        }
    }

    private void buildVendorQuotationTradeStastics(List<VendorQuotationTradeStastics> vendorQuotationTradeStastics, List<Map<String, Object>> vendors) {
        if (vendors != null
                && vendors.size() > 0
                && vendorQuotationTradeStastics != null
                && vendorQuotationTradeStastics.size() > 0){
            vendors.forEach(item->{
                String name = (String) item.get("name");
                vendorQuotationTradeStastics.forEach(item2->{
                    String vendor_organization_name = item2.getVendor_organization_name();
                    if (StringUtils.equals(name,vendor_organization_name)){
                        item.put("goodNum",item2.getGoodNum());
                        item.put("amount",item2.getAmount());
                    }
                });
            });
        }


    }





    /**
     * @return 导出虚拟供应商交易统计
     */
    @Path("exportVirtualVendorStatistic")
    @POST
    @Operation(summary = "导出虚拟供应商交易统计", tags = CUSTOM_SERVICE)
    public SingleResponse exportVirtualVendorStatistic(@Parameter VirtualVendorStatisticDto good) {
        /**
         * <field name="inquiryId" class="java.lang.Long"/>inquiry_id
         * 	<field name="inquiryOrganizationName" class="java.lang.String"/>organization_company_name
         * 	<field name="inquiryTime" class="java.lang.String"/>xjsp_time
         * 	<field name="vendorName" class="java.lang.String"/>vendor_organization_name
         * 	<field name="productManager" class="java.lang.String"/>vented_user_name
         * 	<field name="partakeAndQuoteCount" class="java.lang.String"/>quote_count
         * 	<field name="name" class="java.lang.String"/>name
         * 	<field name="brand" class="java.lang.String"/>brand
         * 	<field name="model" class="java.lang.String"/>model
         * 	<field name="spec" class="java.lang.String"/>spec
         * 	<field name="unit" class="java.lang.String"/>unit
         * 	<field name="num" class="java.lang.Double"/>num
         * 	<field name="delivery" class="java.lang.Double"/>delivery
         * 	<field name="address" class="java.lang.String"/>address
         * 	<field name="price" class="java.lang.Double"/>price
         * 	<field name="quotationTime" class="java.lang.String"/>createdTime
         * 	<field name="memo" class="java.lang.String"/>description
         * 	<field name="time" class="java.lang.String"/>createdTime
         * 	<field name="clarifyTips" class="java.lang.String"/>clarify_tips
         * 	<field name="amount" class="java.lang.Double"/>amount
         */
        ReportType reportType = ReportType.get(good.getFileType());
        List<Map<String, Object>> datas = QuotationGoodJdbcUtil.getQuotationGoodList(good, null, null);
        if (datas != null && datas.size() > 0){
            String exportField = "{\"inquiry_id\":\"inquiryId\",\"organization_company_name\":\"inquiryOrganizationName\",\"xjsp_time\":\"inquiryTime\",\"vendor_organization_name\":\"vendorName\",\"vented_user_name\":\"productManager\",\"quote_count\":\"partakeAndQuoteCount\",\"name\":\"name\",\"brand\":\"brand\",\"model\":\"model\",\"spec\":\"spec\",\"unit\":\"unit\",\"num\":\"num\",\"delivery\":\"delivery\",\"address\":\"address\",\"price\":\"price\",\"delivery\":\"delivery\",\"createdTime\":\"quotationTime\",\"description\":\"memo\",\"delivery\":\"delivery\",\"clarify_tips\":\"clarifyTips\",\"amount\":\"amount\"}";
            JSONObject exportJson = JSON.parseObject(exportField);
            List<Map<String, Object>> fileData = datas.stream().map(m -> {
                Map<String, Object> mf = new HashMap<>();
                for (String key : exportJson.keySet()) {
                    if(key.equals("xjsp_time") || key.equals("createdTime")){
                        Date date = (Date) m.get(key);
                        log.info("date:{}",date);
                        mf.put(exportJson.getString(key), DateUtil.formatDateTime(date));
                    }else{
                        mf.put(exportJson.getString(key), m.get(key));
                    }
                }
                return mf;
            }).collect(Collectors.toList());
            ReportUtils.exportReport("virtual_account_report", reportType.getId(), fileData);
            return SingleResponse.buildSuccess();
        }else{
            return SingleResponse.buildFailure("-1", "未获取到下载数据");
        }

    }

    @Path("exportVendorTradeStatistic")
    @POST
    @Operation(summary = "导出供应商交易量统计",tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> exportVendorTradeStatistic(@Parameter VendorStatsticsDto vendor){
        ReportType reportType = ReportType.get(vendor.getFileType());
        List<Map<String, Object>> maps = new ArrayList<>();
        maps = getMaps(vendor, null, null);
        /**
         * <field name="quotationTotal" class="java.lang.String"/> 总价(报价)amount
         * 	<field name="quotationNum" class="java.lang.String"/>商品数(报价)goodNum
         * 	<field name="orderGoodsNum" class="java.lang.String"/>商品数(订单)orderGoodNum
         * 	<field name="companyName" class="java.lang.String"/>组织名称name
         * 	<field name="refundNum" class="java.lang.String"/>商品数(退货)de24o0hrtrls
         * 	<field name="orderGoodsTotal" class="java.lang.String"/>总价(订单)orderAmount
         * 	<field name="refundTotal" class="java.lang.String"/>总价(退货)refund_total
         */

        if (maps != null && maps.size() > 0){
//            String exportField = "{\"quotationTotal\":\"quotationTotal\",\"quotationNum\":\"quotationNum\",\"orderGoodsNum\":\"orderGoodsNum\",\"companyName\":\"companyName\",\"refundNum\":\"refundNum\",\"orderGoodsTotal\":\"orderGoodsTotal\",\"refundTotal\":\"refundTotal\"}";
            String exportField = "{\"amount\":\"quotationTotal\",\"goodNum\":\"quotationNum\",\"orderGoodsNum\":\"orderGoodsNum\",\"name\":\"companyName\",\"de24o0hrtrls\":\"refundNum\",\"orderAmount\":\"orderGoodsTotal\",\"refund_total\":\"refundTotal\"}";
            JSONObject exportJson = JSON.parseObject(exportField);
            List<Map<String, Object>> fileData = maps.stream().map(m -> {
                Map<String, Object> mf = new HashMap<>();
                for (String key : exportJson.keySet()) {
                    mf.put(exportJson.getString(key), m.get(key));
                }
                return mf;
            }).collect(Collectors.toList());
            ReportUtils.exportReport("supplier_volume_report", reportType.getId(), fileData);
            return SingleResponse.buildSuccess();
        }else{
            return SingleResponse.buildFailure("-1", "未获取到下载数据");
        }
    }




    @Path("exportVendorProtocolTradeStatistic")
    @POST
    @Operation(summary = "导出协议供应商报价数据",tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> exportVendorProtocolTradeStatistic(@Parameter VendorStatsticsDto vendor){
        try{
            ReportType reportType = ReportType.get(vendor.getFileType());
            List<InternalVendorQuotationVO> maps = VendorStasticsJdbcUtil.queryInnerVendorStatistics(vendor);
            if (maps != null && maps.size() > 0){
                List<Map<String, Object>> fileData = maps.stream().map(m -> {
                    Map<String, Object> mf = new HashMap<>();
                    mf.put("organizationCompanyName",m.getOrganizationCompanyName());
                    mf.put("itime",m.getItime());
                    mf.put("expire",m.getExpire());
                    mf.put("inquiryId",m.getInquiryId());
                    mf.put("id",m.getId());
                    mf.put("name",m.getName());
                    mf.put("brand",m.getBrand());
                    mf.put("spec",m.getSpec());
                    mf.put("model",m.getModel());
                    mf.put("unit",m.getUnit());
                    mf.put("num",m.getNum());
                    mf.put("time",m.getTime());
                    mf.put("vendorOrganizationName",m.getVendorOrganizationName());
                    mf.put("status",m.getStatus());
                    mf.put("winnbid",m.getWinnbid());
                    mf.put("placeorder",m.getPlaceorder());
                    mf.put("manager",m.getManager());
                    mf.put("pretaxPrice",m.getPretaxPrice());
                    return mf;
                }).collect(Collectors.toList());
                ReportUtils.exportReport("work_bench_protocol_quotation_details_report", reportType.getId(), fileData);
                return SingleResponse.buildSuccess();
            }else{
                return SingleResponse.buildFailure("-1", "未获取到下载数据");
            }
        }catch (Exception e){
            return SingleResponse.buildFailure("-1", e.getMessage());
        }


    }


    @Path("exportInnerVendorStatistics")
    @POST
    @Operation(summary = "导出内部供应商报价数据",tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> exportInnerVendorStatistics(@Parameter VendorStatsticsDto vendor){
        try{
            ReportType reportType = ReportType.get(vendor.getFileType());
            List<InternalVendorQuotationVO> maps = VendorStasticsJdbcUtil.queryInnerVendorStatistics(vendor);

            if (maps != null && maps.size() > 0){
                List<Map<String, Object>> fileData = maps.stream().map(m -> {
                    Map<String, Object> mf = new HashMap<>();
                    mf.put("organizationCompanyName",m.getOrganizationCompanyName());
                    mf.put("itime",m.getItime());
                    mf.put("expire",m.getExpire());
                    mf.put("inquiryId",m.getInquiryId());
                    mf.put("id",m.getId());
                    mf.put("name",m.getName());
                    mf.put("brand",m.getBrand());
                    mf.put("spec",m.getSpec());
                    mf.put("model",m.getModel());
                    mf.put("unit",m.getUnit());
                    mf.put("num",m.getNum());
                    mf.put("time",m.getTime());
                    mf.put("vendorOrganizationName",m.getVendorOrganizationName());
                    mf.put("status",m.getStatus());
                    mf.put("winnbid",m.getWinnbid());
                    mf.put("placeorder",m.getPlaceorder());
                    mf.put("manager",m.getManager());
                    mf.put("pretaxPrice",m.getPretaxPrice());
                    mf.put("quotationId",m.getQuotationId());
                    mf.put("inquiryClarifyTime",m.getInquiryClarifyTime());
                    mf.put("inquiryClarify",m.getInquiryClarify());
                    return mf;
                }).collect(Collectors.toList());
                ReportUtils.exportReport("work_bench_supplier_quotation_details_report", reportType.getId(), fileData);
                return SingleResponse.buildSuccess();
            }else{
                return SingleResponse.buildFailure("-1", "未获取到下载数据");
            }
        }catch (Exception e){
            return SingleResponse.buildFailure("-1", e.getMessage());
        }

    }


}
